package routers

import (
	"fmt"
	"gindemo02/middlewares"
	"net/http"
	"reflect"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func RoutersChat(r *gin.Engine) {

	apiRouters := r.Group("/chat", middlewares.InitMiddleware)
	{

		apiRouters.Any("/:model/:action", func(c *gin.Context) {

			model := c.Param("model")
			action := c.Param("action")

			// 处理消息
			// 根据需要选择并调用适当的构造函数
			controllerName := strings.Title(model) + "Controller" // 这可以是一个动态变化的值

			constructor, ok := Constructors[controllerName]

			if !ok {
				fmt.Println("Constructor not found")
				return
			}

			controller := constructor()

			// 获取UserController的反射类型（'UserController'）
			controllerValue := reflect.ValueOf(controller)

			// 获取方法名为'Test'的方法
			reflectMethod := controllerValue.MethodByName(strings.Title(action))

			// 检查方法是否存在
			if !reflectMethod.IsValid() {
				fmt.Println("Method not found")
				return
			}

			conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
			if err != nil {
				c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
				return
			}

			reflectMethod.Call([]reflect.Value{reflect.ValueOf(c), reflect.ValueOf(conn)})

		})

	}

}
